<template>
	<view class="container">
		<!-- 搜索框 -->
		<view class="search-box">
			<u-search v-model="searchValue" placeholder="请输入单位名称搜索" bg-color="#f5f5f5" border-color="#ddd"
				borderRadius="16rpx" height="70rpx" padding="0 15rpx 0 70rpx" placeholder-color="#999"
				@custom="onSearch">
				<view slot="prefix" class="search-icon">
					<u-icon name="search" color="#999" size="30rpx"></u-icon>
				</view>
			</u-search>
		</view>
		<!-- 近期使用 -->
		<view class="recent-use" v-if="this.cacheUnit.length>0">
			<view class="recent-title">近期使用</view>
			<view class="recent-tags">
				<view class="tag" v-for="(item,index) in cacheUnit" :key="index" @click="goBillDetail(item)">
					{{item.name}}
				</view>
			</view>
		</view>
		<u-index-list :indexList="indexList" inactiveColor="#165DFF">
			<template v-for="(item, index) in itemArr">
				<!-- #ifdef APP-NVUE -->
				<u-index-anchor :text="indexList[index]" :key="index"></u-index-anchor>
				<!-- #endif -->
				<u-index-item :key="index">
					<!-- #ifndef APP-NVUE -->
					<u-index-anchor :text="indexList[index]"></u-index-anchor>
					<!-- #endif -->
					<view class="list" v-for="(item1, index1) in item" :key="index1">
						<view class="list__item" @click="goBillDetail(item1)">
							<image class="list__item__avatar" src="/static/assets/logoIcon.png"></image>
							<text class="list__item__user-name">{{item1.name}}</text>
						</view>
						<u-line></u-line>
					</view>
				</u-index-item>
			</template>
		</u-index-list>
	</view>
</template>
<script>
	import Pinyin from '@/utils/pinyin.js'
	import {
		postAgencyShow
	} from '@/api/homeApi.js'
	export default {
		data() {
			return {
				searchValue: '',
				indexList: [],
				names: [],
				filteredList: [],
				cacheUnit: []
			}
		},
		computed: {
			itemArr() {
				const pinyin = new Pinyin();
				const validFirstChars = new Set(); // 用于收集去重后的有效首字母
				const tempGroups = {}; // 临时存储分组数据

				// 第一步：收集所有有效首字母并临时分组
				this.filteredList.forEach(item => {
					let firstChar = item.agencyName.charAt(0);

					// 处理汉字首字母
					if (/[\u4e00-\u9fa5]/.test(firstChar)) {
						firstChar = pinyin.getCamelChars(firstChar).toUpperCase();
					} else {
						// 非汉字转大写
						firstChar = firstChar.toUpperCase();
					}

					// 只保留A-Z的有效首字母
					const code = firstChar.charCodeAt(0);
					if (code >= 65 && code <= 90) {
						validFirstChars.add(firstChar);
						// 初始化分组数组（如果不存在）
						if (!tempGroups[firstChar]) {
							tempGroups[firstChar] = [];
						}
						// 添加当前项到对应分组
						tempGroups[firstChar].push({
							name:item.agencyName,
							agencyID:item.agencyID,
							cantonID:item.cantonID
						});
					}
				});

				// 第二步：将首字母转为数组并排序（A-Z顺序）
				const sortedChars = Array.from(validFirstChars).sort();
				this.indexList = sortedChars
				// 第三步：根据排序后的首字母生成最终分组数组
				return sortedChars.map(char => tempGroups[char]);
			}
		},
		async created() {
			await this.postAgencyShowFun()
			await this.onSearch()
		},
		onShow() {
		const arr = uni.getStorageSync('recentUnit')||[]
		console.log('缓存的recentUnit', arr)
		this.cacheUnit = arr	
		},
		methods: {
			async postAgencyShowFun() {
				uni.showLoading({
					title: '加载中'
				})
				const res = await postAgencyShow()
				console.log('res', res)
				if (res.result == 0) {
					// this.names = res.agencyList.map(item => item.agencyName)
					this.names = res.agencyList
					console.log('==', this.names)
					uni.hideLoading()
				} else {
					uni.$u.toast(res.message || '加载失败')
					uni.hideLoading()
				}
			},
			navigateBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			goBillDetail(params) {
				console.log('==',params)
				const arr = uni.getStorageSync('recentUnit') || []
				if (arr.length > 0) {
					// 判断是否已存在（以name作为唯一标识）
					const isExist = arr.some(item => item.name === params.name);
					// 若不存在则插入
					if (!isExist) {
						arr.unshift(params);
						console.log("插入成功，更新后的数组：", arr);
					} else {
						console.log("对象已存在，无需插入");
					}
				} else {
					arr.unshift(params);
				}
				uni.setStorage({
					key: 'recentUnit',
					data: arr.slice(0, 4) //控制显示几个
				})
				uni.navigateTo({
					url: '/pages/ticket/unitTicket',
					success:()=> {
						uni.$emit('billingEntity', params)
					}
				});
			},
			onSearch(val) {
				const keyword = this.searchValue.trim().toLowerCase(); // 去除空格并转小写（忽略大小写）
				if (!keyword) {
					// 如果关键词为空，显示所有数据
					this.filteredList = this.names;
					return;
				}
				this.filteredList = this.names.filter(item => {
				  // 取对象的name属性进行匹配（根据实际需求替换为目标属性）
				  const nameStr = String(item.agencyName).toLowerCase(); // 转小写统一匹配规则
				  const keywordLower = keyword.toLowerCase(); // 关键词也转小写，确保大小写不敏感
				  return nameStr.includes(keywordLower);
				});
			},

		}
	}
</script>

<style lang="scss" scoped>
	.list {
		&__item {
			@include flex;
			padding: 20rpx;
			align-items: center;

			&__avatar {
				width: 50rpx;
				height: 50rpx;
				border-radius: 3px;
			}

			&__user-name {
				font-size: 16px;
				margin-left: 10px;
				color: $u-main-color;
			}
		}
	}
	// /deep/ .u-index-list__letter {
	//   top: auto !important; /* 使用 !important 确保覆盖组件默认样式 */
	// }
	.container {
		background-color: #ffffff;
		min-height: 100vh;
		/* 预留底部空间 */
	}

	/* 搜索框样式 */
	.search-box {
		margin: 30rpx 32rpx;
		position: relative;
	}

	.search-input {
		width: 100%;
		padding: 24rpx 24rpx 24rpx 80rpx;
		border: 2rpx solid #eeeeee;
		border-radius: 16rpx;
		font-size: 28rpx;
	}

	.search-icon {
		position: absolute;
		left: 32rpx;
		top: 50%;
		transform: translateY(-50%);
	}

	/* 近期使用样式 */
	.recent-use {
		margin: 0 32rpx 30rpx;
	}

	.recent-title {
		font-size: 32rpx;
		margin-bottom: 24rpx;
		color: #333333;
	}

	.recent-tags {
		display: flex;
		gap: 24rpx;
		flex-wrap: wrap;
	}

	.tag {
		padding: 16rpx 32rpx;
		background-color: #f5f5f5;
		border-radius: 40rpx;
		font-size: 28rpx;
		color: #333333;
	}

	/* 单位列表样式 */
	.unit-list {
		margin: 0 32rpx;
	}

	.unit-group {
		margin-bottom: 40rpx;
	}

	.group-letter {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 16rpx;
		color: #666666;
	}

	.unit-item {
		display: flex;
		align-items: center;
		padding: 24rpx 0;
		border-bottom: 2rpx solid #eeeeee;
	}

	.unit-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 16rpx;
		background-color: #4285f4;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 24rpx;
		color: #ffffff;
		font-size: 28rpx;
	}

	.unit-name {
		font-size: 32rpx;
		color: #333333;
	}

	/* 右侧字母索引 */
	.letter-index {
		position: fixed;
		right: 16rpx;
		top: 50%;
		transform: translateY(-50%);
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.letter-item {
		font-size: 24rpx;
		color: #666666;
		text-align: center;
		width: 40rpx;
		height: 40rpx;
		line-height: 40rpx;
	}

	.letter-item.active {
		color: #4285f4;
		font-weight: bold;
	}
</style>